
import React from 'react';
import { matchPath } from 'react-router';

export function getAsyncActions(app) {
    try {
        let actions = [];
        app._models.forEach((model) => {
            if (model.effects) {
                actions = actions.concat(Object.keys(model.effects));
            }
        });
        return actions;
    } catch (e) {
        return [];
    }
}
export function isArray(element) {
    return Object.prototype.toString.call(element) === '[object Array]';
}
export function findRouteByUrl(routes, url) {
    const rtn = [];
    const queryIndex = url.indexOf('?');
    if (queryIndex > -1) {
        url = url.slice(0, queryIndex);
    }
    if (url.length > 1 && url[url.length - 1] === '/') {
        url = url.slice(0, -1);
    }
    searchRoutes(routes, (route) => {
        const match = matchPath(url, route.props);
        if (match) {
            if (match.url === url) {
                rtn.push(route);
            }
        }
    });
    return rtn;
}
export function searchRoutes(r, callback) {
    function searchPaths(routes) {
        if (isArray(routes)) {
            routes.forEach((route) => {
                searchPaths(route);
            });
        }
        if (typeof routes === 'object' && routes.props && routes.props.children) {
            React.Children.forEach(routes.props.children, (route) => {
                searchPaths(route);
            });
        }
        if (typeof routes === 'object' && routes.props && routes.props.path) {
            callback(routes);
        }
    }
    searchPaths(r);
}

export const deepClone = (target) => {
    let clone = {};
    if (!target || typeof target !== 'object') {
        return target;
    }
    if (isArray(target)) {
        clone = target.map(item => deepClone(item));
        return clone;
    }
    for (let key in target) {
        if (target.hasOwnProperty(key)) {
            clone[key] = deepClone(target[key]);
        }
    }
    return clone;
};
